package net.midnighttd.engine.view.sprite;

import net.midnighttd.engine.ResourceManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.ArrayList;

/**
 * Author: Adam Scarr
 * Date: 19/04/2009
 * Time: 12:32:01 PM
 */
public class Animation {
    private long frameDuration;
    private ArrayList<Image> frames = new ArrayList<Image>();
    private long startTime;
    private String name;
    private String playnext;


    public Animation(int fps) {
        rewind();
        setFPS(fps);
    }

    /**
     * Used to create a new animation from an image.
     * @param name      The name of the animation
     * @param filename  The filename of the image
     * @param index     The row in the image that the animation is in (0-based)
     * @param frames    The number of frames in the animation
     * @param fps       The number of frames per second to play.
     * @param width     The width of each frame.
     * @param height    The height of each frame.
     */
    public Animation(String name, String filename, int index, int frames, int fps, int width, int height, String playnext) {
        this.name = name;
        this.playnext = playnext;
        setFPS(fps);
        rewind();

        load_from_image(filename, index, frames, width, height);
    }

    private void load_from_image(String filename, int index, int frames, int width, int height) {
        BufferedImage raw = ResourceManager.getBufferedImage(filename, BufferedImage.TYPE_4BYTE_ABGR);
        int y = height * index;
        for(int i = 0; i < frames; i++) {
            this.frames.add(raw.getSubimage(i * width, y, width, height));
        }
    }

    public void setFPS(int fps) {
        frameDuration = (long)((1.0 / fps) * 1000000000);
    }

    public void addFrame(Image frame) {
        frames.add(frame);
    }

    public long getFrameDuration() {
        return frameDuration;
    }

    public void rewind() {
        startTime = System.nanoTime();
    }

    public void gotoFrame(int frame) {
        startTime = System.nanoTime() - (frame * frameDuration);
    }

    public String getName() {
        return name;
    }

    public Image getFrame() {
        long elapsedTime = System.nanoTime() - startTime;
        if(elapsedTime < 0) return frames.get(0);
        int frame = (int)(elapsedTime / frameDuration);

        if(playnext.equals("")) {
             frame %= frames.size();
        }

        if(frame >= frames.size()) {
            return null;
        }

        //System.out.println(System.nanoTime() + ": " + elapsedTime + "nanoseconds elapsed, frame " + frame);
        return frames.get(frame);
    }

    public Image getFrame(int i) {
        return frames.get(i);
    }

    public String getNextState() {
        return playnext;
    }
}
